iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
Vue.js

新手學習Vue.js與實作之旅系列 第 22

Day22 Vue 動態元件 & KeepAlive

  • 分享至 

  • xImage
  •  

先前在 Day9 Vue指令- 條件渲染 內容中,有提到 v-if 可以依照條件判斷來決定內容是否呈現在畫面上,而今天的內容將介紹另外一種方法來實現動態控制元件的渲染~

如何更簡潔地動態控制元件?

透過使用 Vue 的 <component>元素和特殊的屬性 is 來實現,其中 v-bind:is (簡寫為:is)傳入的值為被註冊的元件名或是導入的元件對象。

以下是官方文件的範例

<component :is="activeComponent" />

KeepAlive 元件是什麼?

KeepAlive 是 Vue 提供的一個內置元件,使得元件經過切換後仍可以保留緩存其狀態,適合應用在分頁切換、表單輸入頁面。

KeepAlive 元件如何使用?

將要緩存的動態元件寫在模板中的<keep-alive> 標籤裡。

以下是官方文件的範例

<!-- 非活躍的組件將會被緩存! -->
<KeepAlive>
  <component :is="activeComponent" />
</KeepAlive>

由於 KeepAlive 元件預設會緩存內部所有元件實例,若緩存的元件數量過多,便可能會影響效能,因此透過以下這些 KeepAlive 的屬性,可以限制要緩存的元件。

  • include

    只會緩存 include 指定的元件實例。

以下是官方文件的範例

<KeepAlive include="a,b">
  <component :is="view" />
</KeepAlive>
  • exclude

    緩存 exclude 指定以外的其他元件實例。
<KeepAlive exclude="c,d">
  <component :is="view" />
</KeepAlive>

include 和 exclude 的 prop 值,除了以英文逗號分隔的字符串外,還可以是一個正則表達式,或是包含這兩種類型的一個數組。

以下是官方文件的範例

<!-- 正則表達式 (需使用 `v-bind`) -->
<KeepAlive :include="/a|b/">
  <component :is="view" />
</KeepAlive>

<!-- 數組 (需使用 `v-bind`) -->
<KeepAlive :include="['a', 'b']">
  <component :is="view" />
</KeepAlive>
  • max

    用於限制可以被緩存的元件數量,若緩存的實例數量即將超過指定的最大值,則最久沒有被訪問的緩存實例將被銷毀,以便為新的實例騰出空間。
<KeepAlive :max="8">
  <component :is="activeComponent" />
</KeepAlive>

參考資源

https://book.vue.tw/CH2/2-3-async-dynamic-components.html
https://zh-hk.vuejs.org/guide/essentials/component-basics.html#dynamic-components
https://hackmd.io/@ivaSrwTTSkC1jb66rpGfnQ/rJxzYnyB9


上一篇
Day21 Vue元件 - Transition
下一篇
Day23 Vue元件 - Teleport
系列文
新手學習Vue.js與實作之旅24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言